<template>
    <div class="section-body">
        <flexbox justify="flex-end" class="btn-group header-btn" v-if="!disabled">
            <a-button type="primary" @click="handleSave">保存</a-button>
        </flexbox>
        <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
            <a-row :gutter="24">
                <a-col :span="20">
                    <a-form-item label="版本号" name="versionNumber">
                        <flexbox style="width: 100%">
                            <span v-if="disabled">
                                {{ form.versionNumber }}
                            </span>
                            <div v-else>
                                <a-select
                                    v-model:value="form.versionNumber"
                                    @change="handleSelectVersionNumber"
                                    style="width: 120px; margin-right: 8px"
                                    v-if="versionNumberList.length"
                                >
                                    <a-select-option :key="item.versionNumber" v-for="item of versionNumberList">
                                        {{ item.versionNumber }}
                                    </a-select-option>
                                </a-select>
                                <flexbox v-if="!versionNumberList.length">
                                    <span>暂无可用的版本号,</span>
                                    <a class="margin-l-8" @click="handleCreateCal">点击创建</a>
                                </flexbox>
                            </div>
                        </flexbox>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="版本名称" name="versionName">
                        <div style="width: 100%">
                            <span v-if="disabled">
                                {{ form.versionName }}
                            </span>
                            <a-input v-model:value="form.versionName" placeholder="请输入版本名称限制200个字" :maxlength="200" v-else />
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="预计交付时间" name="expectTime">
                        <div style="width: 100%">
                            <span v-if="disabled || (detail.belongLine && versionNumberList.length)">{{ $filters.dateFilter(form.expectTime) }}</span>
                            <h-date-picker-cell :disabledDate="false" v-model:value="form.expectTime" v-else />
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20" v-if="form.processType === '1'">
                    <a-form-item label="交付模式" name="deliveryMode">
                        <div style="width: 100%">
                            <span v-if="disabled">
                                {{ form.deliveryMode === '1' ? '项目模式' : '迭代模式' }}
                            </span>
                            <a-select placeholder="请选择" v-model:value="form.deliveryMode" v-else>
                                <a-select-option key="1"> 项目模式 </a-select-option>
                                <a-select-option key="2"> 迭代模式 </a-select-option>
                            </a-select>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="系统类型" name="requestSystem">
                        <div style="width: 100%">
                            <span>
                                {{ $filters.valToNameFilter('systemType', form.systemType) }}
                            </span>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="流程状态">
                        <div style="width: 100%">
                            <span>{{ $filters.valToNameFilter('processStatus', form.processStatus) }}</span>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="流程类型" name="processType">
                        <div style="width: 100%">
                            <!-- form.status !== '1' ||  -->
                            <span v-if="+form.processStatus > 1 || form.systemType !== '3' || disabled">
                                {{ $filters.valToNameFilter('processType', form.processType) }}
                            </span>
                            <div v-else>
                                <a-select placeholder="请选择" v-model:value="form.processType">
                                    <a-select-option v-for="item of dicOptions.processType" :key="item.code">
                                        {{ item.dimensionName }}
                                    </a-select-option>
                                </a-select>
                            </div>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="开始时间">
                        <div style="width: 100%">
                            <span>{{ $filters.dateFilter(form.startTime) }}</span>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="发布时间">
                        <div style="width: 100%">
                            <span>{{ $filters.dateFilter(form.onlineTime) }}</span>
                        </div>
                    </a-form-item>
                </a-col>
                <a-col :span="20">
                    <a-form-item label="负责人">
                        <div style="width: 100%">
                            <span>{{ detail.createUser }}</span>
                        </div>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>

        <a-modal title="预计交付时间调整原因" centered v-model:visible="visible" :width="800">
            <a-form layout="inline" ref="modalRuleFormRef" :model="subForm" :rules="subRules">
                <a-form-item label="原因" name="changeOpinion">
                    <a-textarea
                        placeholder="请输入需求调整原因限制255个字"
                        showCount
                        :maxlength="255"
                        auto-size
                        v-model:value="subForm.changeOpinion"
                    />
                </a-form-item>
            </a-form>

            <template #footer>
                <flexbox justify="flex-end" class="btn-group">
                    <a-button type="primary" @click="handleOk">提交</a-button>
                </flexbox>
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { reg1 } from '@/config/pattern';
import { HDatePickerCell, HCascader } from '@/components';
import { message } from 'ant-design-vue';
import api from '@/api';
import moment from 'moment';
import { defineComponent, ref, unref, reactive, toRefs, computed, watch, nextTick } from 'vue';
import { deepClone } from '@/utils/util';
export default defineComponent({
    name: 'BaseInfo',
    components: {
        HDatePickerCell,
        HCascader
    },
    props: {
        detail: { type: Object, default: () => ({}) },
        disabled: { type: Boolean, default: false },
        stepStatus: { type: String, default: '' },
        systemInfo: { type: Object, default: () => ({}) }
    },
    emits: ['detailChange', 'save'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>();
        const modalRuleFormRef = ref<any>();
        const state = reactive<Recordable>({
            form: {
                versionName: '',
                versionNumber: '',
                expectTime: '',
                startTime: '',
                onlineTime: '',
                isBasicLineVersion: '',
                processStatus: '',
                processType: '',
                status: '',
                system: null,
                systemType: '',
                pmpVersionManagementDTO: null,
                changeOpinion: '',
                catalogCode: '',
                catalogName: '',
                deliveryMode: ''
            },
            subForm: {
                changeOpinion: ''
            },
            relateInfo: {},
            oldData: {}, // 保存一份旧数据
            versionNumberList: [],
            visible: false,
            subRules: {
                changeOpinion: [{ required: true, message: '调整原因不能为空', trigger: blur }]
            }
        });
        const validateRepeatName = async (rule: any, value: any) => {
            if (value) {
                const { system } = state.form;
                const query = {
                    system,
                    versionName: value,
                    id: props.detail.id
                };
                const { success, errorMsg } = await api.versionModel.validVersionRepeat(query, { cancelDuplicated: true });
                return success ? Promise.resolve() : Promise.reject(errorMsg);
            } else {
                return Promise.reject('版本名称不能为空');
            }
        };
        const validateRepeatNumber = async (rule: any, value: any) => {
            if (value) {
                const { system } = state.form;
                const query = {
                    system,
                    versionNumber: value,
                    id: props.detail.id
                };
                const { success, errorMsg } = await api.versionModel.validVersionRepeat(query, { cancelDuplicated: true });
                return success ? Promise.resolve() : Promise.reject(errorMsg);
            } else {
                return Promise.reject('版本号不能为空');
            }
        };
        const rules = computed(() => {
            const rules = {
                versionName: [{ required: true, validator: validateRepeatName, trigger: 'blur' }],
                versionNumber: [
                    { required: true, validator: validateRepeatNumber, trigger: 'blur' }
                ],
                expectTime:
                    props.detail.belongLine && state.versionNumberList.length
                        ? []
                        : [{ required: true, message: '预计交付日期不能为空', trigger: 'blur' }],
                processType:
                    +state.form.processStatus > 1 || state.form.systemType !== '3'
                        ? []
                        : [{ required: true, message: '流程类型不能为空', trigger: 'blur' }],
                deliveryMode: [{ required: true, message: '交付模式不能为空', trigger: 'blur' }]
            };
            return props.disabled ? {} : rules;
        });
        const validate = () => {
            return new Promise((resolve) => {
                unref(ruleFormRef)
                    ?.validate()
                    .then(
                        () => {
                            resolve({
                                res: true,
                                errorMsg: null
                            });
                        },
                        () => {
                            resolve({
                                res: false,
                                errorMsg: null
                            });
                        }
                    );
            });
        };
        const handleSave = () => {
            if (props.stepStatus && state.oldData.expectTime !== state.form.expectTime) {
                state.visible = true;
                nextTick(() => {
                    unref(modalRuleFormRef).clearValidate();
                });
                state.subForm.changeOpinion = '';
                state.form.changeOpinion = '';
            } else {
                state.oldData = deepClone(state.form);
                emit('save', 5);
            }
        };

        const handleOk = () => {
            unref(modalRuleFormRef)
                .validate()
                .then(() => {
                    state.form.changeOpinion = state.subForm.changeOpinion;
                    state.visible = false;
                    emit('save', 5);
                });
        };
        const handleSelectVersionNumber = (val) => {
            const item = state.versionNumberList.find((item) => item.versionNumber === val);
            state.form.pmpVersionManagementDTO = item || null;
            state.form.expectTime = item.onlineTime ? moment(item.onlineTime).format('YYYY-MM-DD HH:mm:ss') : item.onlineTime;
            state.form.versionNumber = val;
        };
        // 搜索系统下的所有可用的版本号
        const getVersionNumberList = async () => {
            const { success, moule, errorMsg } = await api.versionControlModel.findUsableVersions({
                versionNumber: props.detail.versionNumber,
                catalogCode: props.systemInfo.catalogCode
            });
            if (success) {
                state.versionNumberList = [...moule];
            } else {
                message.error(errorMsg);
            }
        };
        const init = () => {
            Object.keys(state.form).forEach((key) => {
                state.form[key] = props.detail[key];
            });

            state.oldData = deepClone(state.form);
            if (!props.disabled) {
                getVersionNumberList();
            }
        };

        watch(
            () => state.form.processType,
            (n: string) => {
                emit('detailChange', {
                    processType: n
                });
            }
        );

        init();
        return {
            ruleFormRef,
            modalRuleFormRef,
            ...toRefs(state),
            rules,
            validate,
            handleSave,
            handleSelectVersionNumber,
            handleOk
        };
    }
});
</script>
<style lang="less">
@import './RelateProcess/CheckProcess/styles/index.less';
.section-body {
    &-title {
        font-size: 24px;
        color: @title-font-color;
        font-weight: bold;
    }
    .btn-group {
        margin: 0 12px 8px 0;
        button + button {
            margin-left: 8px;
        }
    }
}
</style>

